package com.zr.action;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

import javax.annotation.Resource;
import javax.jws.soap.SOAPBinding;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.interceptor.ServletResponseAware;
import org.apache.struts2.interceptor.SessionAware;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.opensymphony.xwork2.ActionSupport;
import com.zr.model.Role;
import com.zr.model.User;
import com.zr.service.UserService;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
@Controller
@Scope(value="prototype")
public class UserAction extends  ActionSupport  implements  ServletResponseAware,SessionAware{
	
	
	private String jzw;
	public String getJzw() {
		return jzw;
	}
	public void setJzw(String jzw) {
		this.jzw = jzw;
	}

	private  User user;
	private  HttpServletResponse  resp;
	private Map session; 
    public User getUser() {
		return user;
	}
	public void setUser(User user) {
		this.user = user;
	}
		
	@Resource
	private  UserService  userService;	
	
	public void login() throws IOException{
	  User currentuser =userService.findUserByuserNameanduserPsw(user);
	  PrintWriter pw= resp.getWriter();
	  if(null!=currentuser){
		  session.put("user",currentuser);	
		  if("on".equals(jzw)){
				Cookie namecookie = new Cookie("uname",currentuser.getUname());
				Cookie pswcookie = new Cookie("upsw", currentuser.getUpsw());
				namecookie.setMaxAge(60*60);
				pswcookie.setMaxAge(60*60);
				resp.addCookie(namecookie);
				resp.addCookie(pswcookie);				
			}	
			pw.write("1");
	  }else{
		  pw.write("0");
	  }
		pw.flush();
		pw.close();
	}
	
	@Override
	public void setServletResponse(HttpServletResponse response) {
		this.resp = response;		
	}
	public String showMain(){
		if(null==session.get("user")){
			return "err";
		}else{
			return "suc";
		}
	}
	
	public void show() throws IOException{
		
		User u=(User)session.get("user"); 
		
		Role r=userService.findrole(u.getRole().getRid());
	
		JSONArray j=userService.findfuns(-1, r.getFuncs());
		resp.setContentType("text/html;charset=utf-8"); 
		PrintWriter pw = resp.getWriter();
		pw.write(j.toString());
		pw.flush();
		pw.close();
		
	}
	@Override
	public void setSession(Map<String, Object> session) {
		this.session=session;
		}
}
